package com.ias.log.appender;


import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.AppenderBase;
import ch.qos.logback.core.Layout;
import ch.qos.logback.core.encoder.Encoder;
import ch.qos.logback.core.status.ErrorStatus;

import com.ias.log.service.LogService;
import com.ias.log.util.SpringUtils;

import java.util.Date;
import java.util.Map;

/**
 *
 * 自定义Appender
 *
 */
public class ErrorLogAppende<E> extends AppenderBase<E> {


    protected Layout<E> layout;
    protected Encoder<E> encoder;

    @Override
    public void start() {
        int errors = 0;
        if (this.layout == null && this.encoder == null) {
            this.addStatus(
                    new ErrorStatus("No layout && encoder set for the appender named \"" + this.name + "\".", this));
            ++errors;
        }
        if (errors == 0) {
            super.start();
        }

    }

    @Override
    public void stop() {
        super.stop();
    }

    @Override
    protected void append(E event) {
        LoggingEvent loggingEvent = ((LoggingEvent) event);
        LogService logService = SpringUtils.getBean(LogService.class);
        logService.saveErrorLog(loggingEvent);

    }


    // 日志转换
    private String encodeMessage(E logEvent) {
        if (this.encoder != null) {
            return new String(this.encoder.encode(logEvent));
        }
        return this.layout.doLayout(logEvent);
    }

    // ----------get set----------



    public Layout<E> getLayout() {
        return layout;
    }

    public void setLayout(Layout<E> layout) {
        this.layout = layout;
    }

    public Encoder<E> getEncoder() {
        return encoder;
    }

    public void setEncoder(Encoder<E> encoder) {
        this.encoder = encoder;
    }

}

